package com.dream.tihai.common.error;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @author Valley
 * Created by Valley on 2022/10/24
 * 响应类，处理所有返回值
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class R<T> implements Serializable {

    public static final long VID = 1L;

    /** 成功 */
    public static final int SUCCESS_CODE = 0;
    public static final String SUCCESS_MSG = "操作成功";

    /** 失败 */
    public static final int FAIL_CODE = 500;
    public static final String FAIL_MSG = "操作失败";

    private int code;
    private String msg;
    private T data;

    private static <T> R<T> result(T data, int code, String msg){
        R<T> result = new R<>();
        result.setData(data);
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }

    public static <T> R<T> ok(){
        return result(null, SUCCESS_CODE, SUCCESS_MSG);
    }

    public static <T> R<T> ok(T data){
        return result(data, SUCCESS_CODE, SUCCESS_MSG);
    }

    public static <T> R<T> ok(T data, String msg){
        return result(data, SUCCESS_CODE, msg);
    }

    public static <T> R<T> fail(){
        return result(null, FAIL_CODE, FAIL_MSG);
    }

    public static <T> R<T> fail(T data){
        return result(data, FAIL_CODE, FAIL_MSG);
    }

    public static <T> R<T> fail(String msg){
        return result(null, FAIL_CODE, msg);
    }

    public static <T> R<T> fail(T data, String msg){
        return result(data, FAIL_CODE, msg);
    }

    public static <T> R<T> fail(int code, String msg){
        return result(null, code, msg);
    }

    public static <T> boolean isSuccess(R<T> ret){
        return ret.getCode() == SUCCESS_CODE;
    }

    public static <T> boolean isError(R<T> ret){
        return !isSuccess(ret);
    }


    @Override
    public String toString() {
        String result = "code:" + code +
                ", msg:'" + msg + '\'';
        if (data != null){
            result += ", data:" + data;
        }
        return result;

    }
}
